<template>
  <div class="retrieve-container">
    <!-- 标题部分 -->
    <div class="page-header">
      <img src="/logo_02.png" alt="系统Logo" class="system-logo" />
      <el-icon class="header-icon"><Search /></el-icon>
      <h2 class="page-title">文本检索</h2>
    </div>
    
    <!-- 搜索框部分 -->
    <div class="search-header">
      <el-input 
        v-model="searchForm.keyword" 
        placeholder="输入关键词或句子进行检索..."
        clearable
        :disabled="loading"
        @keyup.enter="handleSearch"
        class="search-input-wrapper"
      >
        <template #append>
          <el-button 
            type="primary" 
            @click="handleSearch" 
            :loading="loading"
            :disabled="!searchForm.keyword.trim() || loading"
            class="search-button"
          >
            <el-icon v-if="!loading"><Search /></el-icon>
            <el-icon v-else><Loading /></el-icon>
            搜索
          </el-button>
        </template>
      </el-input>
    </div>
    
    <!-- 搜索类型切换 -->
    <div class="search-tabs">
      <div 
        class="tab-item" 
        :class="{ active: searchForm.searchType === 'simple' }"
        @click="searchForm.searchType = 'simple'"
      >
        简单检索
      </div>
      <div 
        class="tab-item" 
        :class="{ active: searchForm.searchType === 'advanced' }"
        @click="searchForm.searchType = 'advanced'"
      >
        高级检索
      </div>
    </div>
    
    <!-- 相似度滑块 -->
    <div class="similarity-slider">
      <span class="slider-label">相似度阈值：</span>
      <div class="slider-wrapper">
        <el-slider 
          v-model="searchForm.threshold" 
          :min="0.1" 
          :max="1.0" 
          :step="0.01"
          :disabled="loading"
          class="custom-slider"
        ></el-slider>
      </div>
      <span class="slider-value">{{ (searchForm.threshold * 100).toFixed(0) }}%</span>
    </div>
    
    <!-- 高级搜索选项 -->
    <el-card class="advanced-search-card" v-if="searchForm.searchType === 'advanced'">
      <el-form :model="searchForm" label-width="100px" @submit.prevent="handleSearch">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="源语言筛选">
              <el-select v-model="searchForm.lang1" placeholder="选择源语言" :disabled="loading">
                <el-option label="不限" value=""></el-option>
                <el-option v-for="lang in availableLanguages" :key="lang.code" :label="lang.name" :value="lang.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标语言筛选">
              <el-select v-model="searchForm.lang2" placeholder="选择目标语言" :disabled="loading">
                <el-option label="不限" value=""></el-option>
                <el-option v-for="lang in availableLanguages" :key="lang.code" :label="lang.name" :value="lang.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSearch" 
            :loading="loading"
            :disabled="!searchForm.keyword.trim() || loading"
          >
            <el-icon v-if="!loading"><Search /></el-icon>
            <el-icon v-else><Loading /></el-icon>
            {{ loading ? '检索中...' : '检索' }}
          </el-button>
          <el-button 
            @click="resetForm"
            :disabled="loading"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div v-if="loading" class="loading-indicator">
      <el-icon><Loading /></el-icon>
      正在检索相关结果，请稍候...
    </div>

    <div v-else-if="searchResults.length > 0" class="results-container">
      <el-alert 
        :title="`找到 ${totalResults} 条相关结果`" 
        type="success" 
        show-icon 
        style="margin-bottom: 20px;"
      />
      
      <!-- 结果列表 -->
      <div class="results-list">
        <div 
          v-for="result in paginatedResults" 
          :key="result.id" 
          class="result-card"
        >
          <!-- 卡片内容 -->
          <div class="result-content-wrapper">
            <div class="result-title">
              {{ result.title || (result.text1 ? (result.text1.length > 50 ? result.text1.substring(0, 50) + '...' : result.text1) : '多语言对齐文本') }}
            </div>
            <div class="result-description">


              <!-- 第一个语言文本 -->
              <div v-if="result.text1" class="text-section">
                <div class="language-label">{{ result.lang1_display || result.lang1 || '语言1' }}</div>
                <div class="text-content" v-html="highlightText(result.text1, searchForm.keyword)"></div>
              </div>

              <!-- 第二个语言文本 -->
              <div v-if="result.text2" class="text-section">
                <div class="language-label">{{ result.lang2_display || result.lang2 || '语言2' }}</div>
                <div class="text-content" v-html="highlightText(result.text2, searchForm.keyword)"></div>
              </div>

              <!-- 备用显示（当没有text1和text2时） -->
              <div v-if="!result.text1 && !result.text2" v-html="highlightText(
                result.description || '详细介绍了东盟语言对齐的技术框架、实现原理以及在多语言处理中的应用实践。',
                searchForm.keyword
              )"></div>
            </div>
          </div>
          <!-- 收藏按钮 -->
          <div class="result-action">
            <el-icon 
              class="star-icon" 
              :class="{ favorited: result.isFavorited }"
              @click="toggleFavorite(result)"
            >
              <StarFilled v-if="result.isFavorited" />
              <Star v-else />
            </el-icon>
          </div>
        </div>
      </div>
      
      <div class="results-footer">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalResults"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <div v-else-if="hasSearched" class="empty-results">
      <el-empty description="未找到相关结果" />
      <p>请尝试使用不同的关键词或调整搜索策略</p>
    </div>
    
    <el-alert 
      v-if="errorMessage" 
      :title="errorMessage" 
      type="error" 
      show-icon 
      closable
      @close="errorMessage = ''"
    />
  </div>
  <div class="back-btn">
    <BackButton></BackButton>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Loading, Star, StarFilled } from '@element-plus/icons-vue'
import api, { favorites, historySync, searchHistory } from '@/api'
import BackButton from '@/components/BackButton.vue'
import '@/assets/common.css'

const store = useStore()
const route = useRoute()
const router = useRouter()

const loading = ref(false)
const searchResults = ref([])
const errorMessage = ref('')
const hasSearched = ref(false)
const availableLanguages = ref([])

// 分页设置
const currentPage = ref(1)
const pageSize = ref(10)
const totalResults = ref(0)
const totalPages = ref(0)

const searchForm = reactive({
  keyword: '',
  searchType: 'simple', // 'simple' 或 'advanced'
  lang1: '',
  lang2: '',
  threshold: 0.1
})

// 计算当前页显示的结果 - 这里我们使用后端返回的分页结果，所以这个计算属性主要用于前端展示
const paginatedResults = computed(() => {
  return searchResults.value
})

// 获取可用语言列表
const fetchAvailableLanguages = async () => {
  try {
    const response = await api.get('/languages')
    availableLanguages.value = response.data.languages
  } catch (error) {
    console.error('获取语言列表失败:', error)
  }
}

/**
 * 从历史记录还原页面状态
 * @returns {boolean} 是否成功还原
 */
const restoreFromHistory = () => {
  const historyId = route.query.historyId
  if (!historyId) return false
  const snapshot = store.getters['history/byId'](historyId)
  if (!snapshot) {
    ElMessage.info('未找到历史记录，已回退为默认页面')
    return false
  }
  // 精确还原表单与结果状态
  const snapForm = snapshot.form || {}
  searchForm.keyword = snapForm.keyword || ''
  searchForm.searchType = snapForm.searchType || 'simple'
  searchForm.lang1 = snapForm.lang1 || ''
  searchForm.lang2 = snapForm.lang2 || ''
  searchForm.threshold = typeof snapForm.threshold === 'number' ? snapForm.threshold : 0.1
  
  // 还原检索结果（确保是数组）
  searchResults.value = Array.isArray(snapshot.results) ? snapshot.results : []
  
  // 还原分页信息（优先使用快照中的分页信息）
  const pagination = snapshot.pagination || {}
  currentPage.value = pagination.currentPage || 1
  pageSize.value = pagination.pageSize || 10
  // 优先使用快照中的totalResults，如果不存在则使用results数组长度
  totalResults.value = typeof pagination.totalResults === 'number' 
    ? pagination.totalResults 
    : (searchResults.value.length > 0 ? searchResults.value.length : 0)
  totalPages.value = pagination.totalPages || Math.ceil(totalResults.value / pageSize.value)
  
  // 还原搜索状态
  hasSearched.value = snapshot.hasSearched ?? true
  errorMessage.value = ''
  loading.value = false
  
  // 如果有关键词但无结果，确保hasSearched为true以显示"未找到相关结果"提示
  if (searchForm.keyword && searchResults.value.length === 0 && totalResults.value === 0) {
    hasSearched.value = true
  }
  
  return true
}

// 页面加载时：先还原历史，再加载语言列表（不触发检索请求）
onMounted(() => {
  const restored = restoreFromHistory()
  fetchAvailableLanguages()
  // 如需将历史访问记录写入浏览器历史状态，可使用HTML5 History API（可选）
  if (restored) {
    const state = { historyId: route.query.historyId }
    window.history.replaceState(state, '', router.resolve({ name: 'TextRetrieve', query: { historyId: route.query.historyId } }).href)
  }
})

const handleSearch = async () => {
  if (!searchForm.keyword.trim()) {
    ElMessage.warning('请输入检索关键词')
    return
  }

  loading.value = true
  errorMessage.value = ''
  hasSearched.value = false

  try {
    // 调用后端API进行检索
    const params = {
      keyword: searchForm.keyword.trim(),
      search_type: searchForm.searchType || 'simple',
      lang1: searchForm.lang1 || undefined,
      lang2: searchForm.lang2 || undefined,
      threshold: searchForm.threshold || 0.1,
      page: currentPage.value,
      per_page: pageSize.value
    }
    
    const response = await api.get('/search', { params })
    searchResults.value = response.data.results
    totalResults.value = response.data.total
    currentPage.value = response.data.page
    pageSize.value = response.data.per_page
    totalPages.value = response.data.total_pages
    
    // 检查收藏状态
    await checkFavoriteStatus()
    
    hasSearched.value = true
    ElMessage.success(`检索成功，找到 ${response.data.total} 条相关结果`)

    // 保存历史记录到本地store（不触发后端请求的还原用）
    const snapshot = {
      form: {
        keyword: searchForm.keyword,
        searchType: searchForm.searchType,
        lang1: searchForm.lang1,
        lang2: searchForm.lang2,
        threshold: searchForm.threshold
      },
      results: searchResults.value,
      pagination: {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        totalResults: totalResults.value,
        totalPages: totalPages.value
      },
      hasSearched: hasSearched.value
    }
    const id = await store.dispatch('history/save', {
      type: 'retrieve',
      routeName: 'TextRetrieve',
      snapshot
    })
    // 更新地址栏的历史参数（便于分享/再次还原）
    router.replace({ name: 'TextRetrieve', query: { historyId: id } })
    
    // 保存到数据库（search_history表）
    try {
      const token = localStorage.getItem('token')
      if (token) {
        await searchHistory.save({
          keyword: searchForm.keyword,
          search_type: searchForm.searchType,
          lang1: searchForm.lang1 || null,
          lang2: searchForm.lang2 || null,
          threshold: searchForm.threshold,
          result_count: totalResults.value,
          page_state: snapshot
        })
      }
    } catch (e) {
      console.error('保存检索历史记录到数据库失败:', e)
      // 不阻塞用户体验，静默失败
    }
    
    // 异步同步到后端（不阻塞体验）- 保留旧的同步方式作为备用
    try {
      historySync.save({
        history_uid: id,
        type: 'retrieve',
        route_name: 'TextRetrieve',
        summary: `检索: "${snapshot.form.keyword}"（${snapshot.pagination.totalResults}条）`,
        snapshot
      }).catch(() => { /* ignore history sync failure */ })
    } catch (e) { /* ignore history sync try-catch failure */ }
  } catch (error) {
    console.error('检索失败:', error)
    errorMessage.value = error.response?.data?.error || error.message || '检索失败，请稍后重试'
    searchResults.value = []
    totalResults.value = 0
    hasSearched.value = true
  } finally {
    loading.value = false
  }
}

/**
 * 检查收藏状态
 * 批量检查当前页面所有结果的收藏状态
 */
const checkFavoriteStatus = async () => {
  if (searchResults.value.length === 0) return
  
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      // 未登录，所有结果标记为未收藏
      searchResults.value.forEach(item => {
        item.isFavorited = false
        item.favoriteLoading = false
      })
      return
    }
    
    const sentencePairIds = searchResults.value.map(item => item.id)
    const response = await favorites.batchCheck({ sentence_pair_ids: sentencePairIds })
    
    if (response.data.status === 'success') {
      const favoritedIds = response.data.data.favorited_ids || []
      searchResults.value.forEach(item => {
        item.isFavorited = favoritedIds.includes(item.id)
        item.favoriteLoading = false
      })
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
    // 失败时默认标记为未收藏
    searchResults.value.forEach(item => {
      item.isFavorited = false
      item.favoriteLoading = false
    })
  }
}

/**
 * 切换收藏状态
 * @param {Object} row - 表格行数据
 */
const toggleFavorite = async (row) => {
  // 检查登录状态
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录后再收藏')
    return
  }
  
  row.favoriteLoading = true
  
  try {
    if (row.isFavorited) {
      // 取消收藏
      await favorites.removeByPairId(row.id)
      row.isFavorited = false
      ElMessage.success('取消收藏成功')
    } else {
      // 添加收藏
      await favorites.add({ sentence_pair_id: row.id })
      row.isFavorited = true
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    const message = error.response?.data?.message || error.message || '操作失败'
    ElMessage.error(message)
  } finally {
    row.favoriteLoading = false
  }
}

const resetForm = () => {
  searchForm.keyword = ''
  searchForm.searchType = 'simple'
  searchForm.lang1 = ''
  searchForm.lang2 = ''
  searchForm.threshold = 0.1
  searchResults.value = []
  hasSearched.value = false
  errorMessage.value = ''
  currentPage.value = 1
  totalResults.value = 0
}

// 高亮显示搜索文本
const highlightText = (text, keyword) => {
  // 详细调试信息
  console.log('highlightText 调用:', {
    text: text ? text.substring(0, 50) + '...' : 'null',
    keyword,
    textLength: text ? text.length : 0,
    keywordLength: keyword ? keyword.length : 0
  })

  if (!keyword || !text) {
    console.log('返回原因: keyword或text为空')
    return text
  }

  // 转义特殊字符，防止正则表达式错误
  const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  console.log('转义后的关键词:', escapedKeyword)

  try {
    // 使用全局和不区分大小写的正则表达式
    const regex = new RegExp(`(${escapedKeyword})`, 'gi')
    console.log('正则表达式:', regex.toString())

    const testResult = text.match(regex)
    console.log('匹配结果:', testResult)

    const highlightedText = text.replace(regex, '<span class="highlight">$1</span>')
    console.log('高亮后的文本长度:', highlightedText.length)
    console.log('是否包含highlight标签:', highlightedText.includes('highlight'))
    console.log('高亮后的文本片段:', highlightedText.substring(0, 200) + '...')

    return highlightedText
  } catch (error) {
    console.error('正则表达式错误:', error)
    return text
  }
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  handleSearch() // 重新搜索
}

const handleCurrentChange = (newCurrent) => {
  currentPage.value = newCurrent
  handleSearch() // 重新搜索
}
</script>

<style scoped>
/* 色彩变量定义 - 与 style.html 保持一致 */
:root {
  --primary: #a78bfa;
  --primary-light: #ddd6fe;
  --primary-dark: #7c3aed;
  --text: #1e293b;
  --bg: #fdf4ff;
  --card-bg: #ffffff;
  --sidebar-bg: #f3f4f6;
  --border: #e2e8f0;
  --success: #10b981;
  --warning: #f59e0b;
  --shadow: rgba(149, 157, 165, 0.2);
}

.retrieve-container {
  max-width: 1440px;
  margin: 0 auto;
  padding: 2rem;
  min-height: calc(100vh - 200px);
  background-color: var(--bg);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 页面标题样式 */
.page-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 2rem;
}

.system-logo {
  height: 48px;
  width: auto;
  object-fit: contain;
  margin-right: 0.5rem;
}

.header-icon {
  font-size: 1.8rem;
  color: var(--primary);
}

.page-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--primary-dark);
  margin: 0;
}

/* 搜索框部分 */
.search-header {
  display: flex;
  align-items: center;
  margin-bottom: 1.5rem;
  gap: 1rem;
}

.search-input-wrapper {
  background-color: var(--primary-light);
  flex: 1;
}

.search-input-wrapper :deep(.el-input__wrapper) {
  background-color: var(--sidebar-bg);
  border: 1px solid var(--border);
  border-radius: 0.75rem;
  padding: 1rem 1.25rem;
  box-shadow: none;
}

.search-input-wrapper :deep(.el-input__wrapper:hover) {
  border-color: var(--primary);
}

.search-input-wrapper :deep(.el-input__inner) {
  color: var(--text);
  font-size: 1rem;
}

.search-button {
  background-color: var(--primary-dark) !important;
  border-radius: 0.75rem;
  padding: 1rem 1.5rem;
  font-weight: 600;
  height: 65px;
  transition: all 0.2s;
}

.search-button:hover:not(:disabled) {
  background-color: var(--primary) !important;
  border-color: var(--primary) !important;
  color: white !important;
}

.search-button:disabled {
  background-color: var(--primary-light) !important;
  color: var(--text) !important;
  opacity: 0.6;
}

/* 搜索标签页样式 */
.search-tabs {
  display: flex;
  border-bottom: 1px solid var(--border);
  margin-bottom: 1.5rem;
  gap: 0;
}

.tab-item {
  padding: 1rem 1.5rem;
  cursor: pointer;
  position: relative;
  font-weight: 500;
  color: var(--text);
  transition: all 0.2s;
  user-select: none;
}

.tab-item:hover {
  color: var(--primary-dark);
  background-color: var(--primary-light);
}

.tab-item.active {
  color: var(--primary-dark);
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: var(--primary-dark);
  border-radius: 3px 3px 0 0;
}

/* 相似度滑块样式 */
.similarity-slider {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1.5rem;
  padding: 1rem 0;
}

.slider-label {
  font-size: 1rem;
  color: var(--text);
  white-space: nowrap;
  font-weight: 500;
}

.slider-wrapper {
  flex: 1;
  max-width: 500px;
}

.custom-slider :deep(.el-slider__runway) {
  background: var(--border);
  height: 6px;
  border-radius: 3px;
}

.custom-slider :deep(.el-slider__bar) {
  background: var(--primary);
  height: 6px;
  border-radius: 3px;
}

.custom-slider :deep(.el-slider__button) {
  width: 20px;
  height: 20px;
  border: 2px solid var(--primary-dark);
  background-color: var(--primary-dark);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
}

.custom-slider :deep(.el-slider__button:hover) {
  transform: scale(1.2);
}

.slider-value {
  font-size: 1rem;
  color: var(--text);
  min-width: 50px;
  text-align: right;
  font-weight: 600;
}

/* 高级搜索卡片样式 */
.advanced-search-card {
  margin-bottom: 1.5rem;
  background-color: var(--card-bg);
  border: 1px solid var(--border);
  border-radius: 1rem;
  box-shadow: 0 4px 20px var(--shadow);
}

.advanced-search-card :deep(.el-card__body) {
  padding: 2rem;
}

.advanced-search-card :deep(.el-form-item__label) {
  color: var(--text);
  font-weight: 500;
}

.advanced-search-card :deep(.el-select) {
  width: 100%;
}

.advanced-search-card :deep(.el-select .el-input__wrapper) {
  background-color: var(--bg);
  border: 1px solid var(--border);
  border-radius: 0.75rem;
}

.advanced-search-card :deep(.el-select .el-input__wrapper:hover) {
  border-color: var(--primary);
}

.advanced-search-card :deep(.el-button--primary) {
  background-color: var(--primary-dark);
  border-color: var(--primary-dark);
  color: white;
}

.advanced-search-card :deep(.el-button--primary:hover:not(:disabled)) {
  background-color: var(--primary);
  border-color: var(--primary);
}

/* 加载指示器 */
.loading-indicator {
  margin: 3rem 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  color: var(--text);
  font-size: 1rem;
}

.loading-indicator :deep(.el-icon) {
  font-size: 1.5rem;
  color: var(--primary);
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 结果容器 */
.results-container {
  margin-top: 2rem;
  min-height: 400px;
}

/* 结果列表样式 */
.results-list {
  display: flex;
  flex-direction: column;
  gap: 1.25rem;
  margin-bottom: 2rem;
}

/* 结果卡片样式 */
.result-card {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 1.25rem;
  border: 1px solid var(--border);
  border-radius: 0.75rem;
  background-color: var(--card-bg);
  transition: all 0.3s ease;
  min-height: 100px;
}

.result-card:hover {
  background-color: var(--bg);
  box-shadow: 0 4px 12px var(--shadow);
  border-color: var(--primary-light);
}

/* 结果内容区域 */
.result-content-wrapper {
  flex: 1;
  padding-right: 1rem;
}

.result-title {
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: var(--primary-dark);
  font-size: 1.1rem;
  line-height: 1.5;
}

.result-description {
  color: var(--text);
  font-size: 0.95rem;
  line-height: 1.6;
  word-break: break-word;
}

/* 语言文本部分样式 */
.text-section {
  margin-bottom: 1rem;
  position: relative;
}

.text-section:last-child {
  margin-bottom: 0;
}

/* 语言标签样式 */
.language-label {
  display: inline-block;
  background-color:var(--primary);
  color: white;
  padding: 0.25rem 0.75rem;
  border-radius: 0.5rem;
  font-size: 0.75rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.language-label:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

/* 文本内容样式 */
.text-content {
  padding-left: 0.5rem;
  border-left: 3px solid var(--primary-light);
  transition: border-color 0.2s ease;
}

.text-section:hover .text-content {
  border-left-color: var(--primary);
}

/* 收藏按钮样式 */
.result-action {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 40px;
}

.star-icon {
  font-size:3rem;
  color: var(--warning);
  cursor: pointer;
  transition: all 0.2s;
  padding: 0.5rem;
  border-radius: 50%;
}

.star-icon:hover {
  transform: scale(1.2);
  background-color: var(--primary-light);
}

.star-icon.favorited {
  color: var(--warning);
}

/* 高亮样式 - 增强优先级和可见性 */
:deep(.highlight),
.result-description .highlight,
.text-content .highlight {
  background: #ffeb3b !important;
  padding: 0 3px !important;
  box-shadow: 0 2px 4px rgba(255, 107, 53, 0.3) !important;
  border: none !important;
  display: inline !important;
  line-height: 1.2 !important;
  text-shadow: none !important;
  position: relative !important;
  z-index: 10 !important;
  margin: 0 2px !important;
  animation: highlight-pulse 1.5s ease-in-out !important;
}

/* 高亮动画效果 */
@keyframes highlight-pulse {
  0% {
    background: #ffeb3b !important;
    transform: scale(1.05);
  }
  50% {
    background: #ff9800 !important;
  }
  100% {
    background: #ff6b35 !important;
    transform: scale(1);
  }
}

/* 分页样式 */
.results-footer {
  margin-top: 2rem;
  display: flex;
  justify-content: flex-end;
  padding: 1rem 0;
}

.results-footer :deep(.el-pagination) {
  --el-color-primary: var(--primary-dark);
}

.results-footer :deep(.el-pagination .btn-next),
.results-footer :deep(.el-pagination .btn-prev) {
  background-color: var(--card-bg);
  border: 1px solid var(--border);
  color: var(--text);
}

.results-footer :deep(.el-pagination .btn-next:hover),
.results-footer :deep(.el-pagination .btn-prev:hover) {
  background-color: var(--primary-light);
  border-color: var(--primary);
  color: var(--primary-dark);
}

.results-footer :deep(.el-pagination .number) {
  background-color: var(--card-bg);
  border: 1px solid var(--border);
  color: var(--text);
}

.results-footer :deep(.el-pagination .number:hover) {
  background-color: var(--primary-light);
  border-color: var(--primary);
  color: var(--primary-dark);
}

.results-footer :deep(.el-pagination .number.is-active) {
  background-color: var(--primary-dark);
  border-color: var(--primary-dark);
  color: white;
}

/* 空结果样式 */
.empty-results {
  margin-top: 3rem;
  text-align: center;
  padding: 3rem 0;
  min-height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-results :deep(.el-empty__description) {
  color: var(--text);
}

.empty-results p {
  margin-top: 1rem;
  color: var(--text);
  font-size: 1rem;
}

/* 错误提示样式 */
.el-alert {
  margin-top: 1.5rem;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .retrieve-container {
    max-width: 100%;
    padding: 1.5rem;
  }
}

@media (max-width: 768px) {
  .retrieve-container {
    padding: 1rem;
  }

  .page-header {
    margin-bottom: 1.5rem;
    flex-wrap: wrap;
  }

  .system-logo {
    height: 40px;
  }

  .page-title {
    font-size: 1.3rem;
  }

  .search-header {
    flex-direction: column;
    align-items: stretch;
    gap: 0.75rem;
  }

  .search-input-wrapper {
    width: 100%;
  }

  .similarity-slider {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.75rem;
  }

  .slider-wrapper {
    width: 100%;
    max-width: 100%;
  }

  .slider-value {
    align-self: flex-end;
  }

  .result-card {
    flex-direction: column;
    gap: 1rem;
  }

  .result-content-wrapper {
    padding-right: 0;
  }

  .result-action {
    align-self: flex-end;
  }

  .results-footer {
    justify-content: center;
  }

  .results-footer :deep(.el-pagination) {
    flex-wrap: wrap;
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .system-logo {
    height: 36px;
  }

  .page-title {
    font-size: 1.1rem;
  }

  .tab-item {
    padding: 0.75rem 1rem;
    font-size: 0.9rem;
  }

  .result-card {
    padding: 1rem;
  }

  .result-title {
    font-size: 1rem;
  }

  .result-description {
    font-size: 0.9rem;
  }
}
</style>

<style>
/* 全局高亮样式 - 确保不受组件作用域影响 */
.highlight {
  background: #ff6b35 !important;
  box-shadow: 0 2px 4px rgba(255, 107, 53, 0.3) !important;
  border: none !important;
  display: inline !important;
  line-height: 1.2 !important;
  text-shadow: none !important;
  position: relative !important;
  z-index: 10 !important;
  margin: 0 2px !important;
  animation: highlight-pulse 1.5s ease-in-out !important;
}
</style>